﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

namespace Pop
{
    public class Geometry
    {
        
       static public Boolean InterSegReta(Vector2 reta1A,Vector2 reta1B,Vector2 reta2A,Vector2 reta2B,ref Vector2 pti){
            //verifica se há interseção entre segmentos de reta, e caso sim grava o ponto de interseção em pti
            float Denom =  ((reta2B.X - reta2A.X) * (reta1B.Y - reta1A.Y) - (reta2B.Y - reta2A.Y) * (reta1B.X - reta1A.X));
            float s,n; 

            if(Denom != 0)
            {
             s = ((reta2B.X - reta2A.X) * (reta2A.Y - reta1A.Y) - (reta2B.Y - reta2A.Y) * (reta2A.X - reta1A.X)) / Denom;
             n= ((reta1B.X - reta1A.X) * (reta2A.Y - reta1A.Y) - (reta1B.Y - reta1A.Y) * (reta2A.X - reta1A.X)) / Denom;
            if((s > -0.01) & (s < 1.01) & (n > -0.01) & (n < 1.01))
                {
                    pti.X = reta1A.X + (reta1B.X - reta1A.X) * s;
                    pti.Y = reta1A.Y + (reta1B.Y - reta1A.Y) * s;
                    return true;
                }
            }

        return false;
        }
        
        public float distPtSegReta(Vector2 pto, Vector2 segINI, Vector2 segFim){
            float f,g,t;
            Vector2 pt,ptTemp;

            f = (segFim.X - segINI.X);
            g = (segFim.Y - segINI.Y);

            if ((f * f + g * g) != 0){
            t = (f * (pto.X - segINI.X) + g * (pto.Y - segINI.Y)) / (f * f + g * g);

            if (t < 0) t = 0;
            if (t > 1)  t = 1;

            pt.X = segINI.X + f * t;
            pt.Y = segINI.Y + g * t;

                ptTemp = pt- pto;

            return ptTemp.Length();//Math.Sqrt((pt.X - pto.X) ^ 2 + (pt.Y - pto.Y) ^ 2);
            }
            else{
                 ptTemp = pto - segINI;
                return ptTemp.Length();//Math.Sqrt((pto.X - segINI.X) ^ 2 + (pto.Y - segINI.Y) ^ 2);
            }

        }
   
    }
}
